package com.cqeec.waimaidemo.filter;

import com.alibaba.fastjson.JSON;
import com.cqeec.waimaidemo.common.BaseContext;
import com.cqeec.waimaidemo.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
//    检验地址
     public static final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        强制转换
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
//        获取请求的uri
        String uri  =  request.getRequestURI();
//        不需要处理的地址
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/common/**",
                "/front/**"
        };
//        判断当前访问的地址是不是在urls中，需不需要检验
        boolean flag=checkUrls(uri,urls);
        if (flag){
            filterChain.doFilter(request,response);
            return;
        }
        String agent  = request.getHeader("Agent");
//        判断这个请求从哪里发出来的
        if ("backend".equals(agent)){
//            判断session是否为空
            if (request.getSession().getAttribute("employee1")!=null){
//                放行
                Long id =(Long)  request.getSession().getAttribute("employee1");
                BaseContext.setThreadLocal(id);
                filterChain.doFilter(request,response);
                return;
            }
        }
//        未登录的返回到登录页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    private boolean checkUrls(String uri, String[] urls) {
        for(String u:urls){
            boolean match = antPathMatcher.match(u,uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
